// 路由映射配置
import {createRouter, createWebHashHistory} from 'vue-router'

import Add from "../components/Add.vue";
import Home from "../components/Home.vue";
import List from "../components/List.vue";
import Update from "../components/Update.vue";

const router = createRouter({
    history: createWebHashHistory(), // 记录历史路由跳转
    routes: [
        {
            path: '/',
            component: Home,
        },
        {
            path: '/add',
            component: Add,
        },
        {
            path: '/list',
            component: List,
        },
        {
            path: '/update',
            component: Update,
        }
    ]
});

// 路由守卫
//全局前置路由守卫
router.beforeEach((to, from, next) => {
    //to 是目标地包装对象  .path属性可以获取地址
    //from 是来源地包装对象 .path属性可以获取地址
    //next是方法,不调用默认拦截！ next() 放行,直接到达目标组件
    //next('/地址')可以转发到其他地址,到达目标组件前会再次经过前置路由守卫
    console.log(to.path, from.path, next)
    //需要判断，注意避免无限重定向
    // 这里可以进行权限校验，例如判断用户是否登录
    if (to.path === '/index') {
        next()
    } else {
        next('/index')
    }
})
//全局后置路由守卫
router.afterEach((to, from) => {
    console.log(`Navigate from ${from.path} to ${to.path}`);
});


export default router;
